package com.promise.jokerdream.work.signin

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryPenguinStationResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 乐斗驿站工作
class PenguinStationWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "乐斗驿站"

    override val isActWork: Boolean
        get() = true

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询乐斗驿站信息
            val queryResult = gameApi.queryPenguinStation()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    processPenguinStation(response)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 处理乐斗驿站逻辑
     */
    private suspend fun processPenguinStation(response: QueryPenguinStationResponse): WorkResult {
        // 检查是否已领奖
        if (response.ifGotAward == 0) {
            // 未领奖，执行领奖
            val claimResult = gameApi.claimPenguinStation()
            return claimResult.foldWithApiException(
                onSuccess = { claimResponse ->
                    historyManager.addHistory(name, claimResponse.getDescription())
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } else {
            return WorkResult.Success
        }
    }
}